﻿using System.Windows.Input;

namespace Lib.WPF.Core;
/// <summary>
/// 
/// </summary>
public class Command : ICommand {
    /// <summary>
    /// 
    /// </summary>
    public static Command Create(Action Action, Func<bool> Predicate = null) {
        return new Command(Action, Predicate);
    }
    /// <summary>
    /// 
    /// </summary>
    public static Command Create(Action<object> Action, Predicate<object> Predicate = null) {
        return new Command(Action, Predicate);
    }
    /// <summary>
    /// 构造函数
    /// </summary>
    public Command(Action Action) : this(Action, null) { }
    /// <summary>
    /// 构造函数
    /// </summary>
    public Command(Action Action, Func<bool> Predicate) {
        this._Action = Action ?? throw new ArgumentNullException(nameof(Action));
        this._CanExecute = Predicate;
    }
    /// <summary>
    /// 构造函数
    /// </summary>
    public Command(Action<object> Action) : this(Action, null) { }
    /// <summary>
    /// 构造函数
    /// </summary>
    public Command(Action<object> Action, Predicate<object> Predicate) {
        this._Delegate = Action; 
        this._Predicate = Predicate;
    }
    /// <summary>
    /// 
    /// </summary>
    public event EventHandler CanExecuteChanged = (Sender, e) => { };
    /// <summary>
    /// 委托
    /// </summary>
    private readonly Action _Action;
    /// <summary>
    /// 委托（返回布尔值）
    /// </summary>
    private readonly Func<bool> _CanExecute;
    /// <summary>
    /// 委托（参数）
    /// </summary>
    private readonly Action<object> _Delegate;
    /// <summary>
    /// 委托（参数,返回布尔值）
    /// </summary>
    private readonly Predicate<object> _Predicate;
    /// <summary>
    /// 
    /// </summary>
    public bool CanExecute(object Parameter) {
        if (this._Action != null) {
            return this._CanExecute?.Invoke() ?? true;
        }
        if (this._Delegate != null) {
            return this._Predicate?.Invoke(Parameter) ?? true;
        }
        return true;
    }
    /// <summary>
    /// 
    /// </summary>
    public void Execute(object Parameter) {
        if (this._Action != null) {
            this._Action?.Invoke();
        }
        if (this._Delegate != null) {
            this._Delegate?.Invoke(Parameter);
        }
    }
}